package com.houseman.workFlow;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.houseman.workFlow.processer.ProcessContext;
import com.houseman.workFlow.processer.Processer;
import com.houseman.workFlow.processer.impl.CloseProcesser;
import com.houseman.workFlow.processer.impl.DesignerProcesser;
import com.houseman.workFlow.processer.impl.FolderProcesser;
import com.houseman.workFlow.processer.impl.PublishProcesser;
import com.houseman.workFlow.processer.impl.ImportProcesser;
import com.houseman.workFlow.processer.impl.RequestProcesser;
import com.houseman.workFlow.processer.impl.SaveXmlProcesser;
import com.houseman.workFlow.processer.impl.WorkFlowProcesser;

public class WorkFlowFilter implements Filter{

	/**
	 * 初始化
	 */
	public void init(FilterConfig cfg) throws ServletException {
		System.out.println(cfg.getInitParameter("workFlowContext"));
	}

	/**
	 * 处理以/workFlow/开头的所有workFlow请求
	 * 开发模式-->
	 * dev下的所有请求无需登录操作，其它必须登录
	 * 修改模式-->
	 * 所有请求必须在登录状态下执行，且没有流程设计权限，只有流程审批人更改权限
	 * 安全模式-->
	 * 所有请求必须在登录状态下执行，且没有流程设计权限和流程审批人更改权限
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		
		request.setCharacterEncoding("UTF-8");
		
		String uri = req.getRequestURI();
		String action = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
		/**
		 * 流程请求则分发处理
		 */
		Processer processer = null;
		if("/request".equals(action)) { //流程处理页面请求
			processer = new RequestProcesser();
		}else if("/designer".equals(action)) { //流程设计器
			processer = new DesignerProcesser();
		}else if("/publish".equals(action)) { //流程发布请求
			processer = new PublishProcesser();
		}else if("/import".equals(action)){ //导入已有流程图
			processer = new ImportProcesser();
		}else if("/save".equals(action)){ //流程图形至XML文件并下载
			processer = new SaveXmlProcesser();
		}else if("/folder".equals(action)){ //查询所有在库流程或者所有流程文件夹
			processer = new FolderProcesser();
		}else if("/process".equals(action)){ //流程处理请求
			processer = new WorkFlowProcesser();
		}else if("/close".equals(action)){ //关闭流程
			processer = new CloseProcesser();
		}else { //请求失败
			chain.doFilter(request, response);
		}
		
		/**
		 * 处理workFlow请求
		 */
		ProcessContext pc = new ProcessContext(processer);
		pc.proccess(req, res);
	}

	/**
	 * 销毁
	 */
	public void destroy() {
	}
}
